<template>
  <upload-excel :on-success="handleSuccess" />
</template>

<script>
import { reqImpEmp } from '@/api/employees'
export default {
  name: 'Import',
  methods: {
    async handleSuccess({ header, results }) {
      const query = this.$route.query.type
      if (query === 'user') {
        // console.log(1)
        const userRelations = {
          '入职日期': 'timeOfEntry',
          '手机号': 'mobile',
          '姓名': 'username',
          '转正日期': 'correctionTime',
          '工号': 'workNumber'
        }
        const arr = []
        results.forEach((item) => {
        // 准备一个新对象，换掉键，保留值
          const obj = {}
          for (const key in item) {
          // 拿到中文对应的英文键名 key 姓名
            const englishKey = userRelations[key]
            // if (englishKey === 'timeOfEntry' || englishKey === 'correctionTime') {
            if (['timeOfEntry', 'correctionTime', 'birthday'].includes(englishKey)) {
            // 需要处理值
              obj[englishKey] = this.formatExcelDate(item[key], '-')
            } else {
              obj[englishKey] = item[key]
            }
          }
          arr.push(obj)
        })
        console.log(arr)
        await reqImpEmp(arr)
        this.$message.success('恭喜，批量导入成功')
        this.$router.back()
      }
    },
    formatExcelDate(numb, format) {
      const time = new Date((numb) * 24 * 3600000 + 1) // 毫秒
      time.setYear(time.getFullYear() - 70)
      const year = time.getFullYear() + ''
      const month = time.getMonth() + 1 + ''
      const date = time.getDate() - 1 + ''
      if (format && format.length === 1) {
        return year + format + (month < 10 ? '0' + month : month) + format + (date < 10 ? '0' + date : date)
      }
      return year + (month < 10 ? '0' + month : month) + (date < 10 ? '0' + date : date)
    }
  }
}
</script>

<style>

</style>
